﻿using System;
using UnityEngine;
using UnityEngine.Android;

namespace XUBugly
{
    public class XUBuglyMgr
    {
        public static void InitBugly(bool debug, string appIdAndroid, string appIdiOS, LogSeverity logSeverity = LogSeverity.LogException)
        {
            Debug.Log(string.Format("XUBuglyMgr InitBugly debug={0},appIdAndroid={1},appIdiOS={2},logSeverity={3}", debug, appIdAndroid, appIdiOS, logSeverity));

            if (Application.isEditor == false && (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer))
            {
                // 开启SDK的日志打印，发布版本请务必关闭
                BuglyAgent.ConfigDebugMode(debug);

                if (Application.platform == RuntimePlatform.Android)
                {
                    int androidInt = GetAndroidVersion();
                    Debug.Log("XUBuglyMgr androidInt = " + androidInt);

                    bool usesCleartextTraffic = GetUsesCleartextTraffic(androidInt);
                    Debug.Log("XUBuglyMgr usesCleartextTraffic = " + usesCleartextTraffic);

                    //usesCleartextTraffic属性是API 23 之后才加入的
                    if (androidInt >= 23)
                    {
                        if (!usesCleartextTraffic)
                        {
                            ToastText("XUBuglyMgr 需要开启 android:usesCleartextTraffic");
                            Debug.LogError("XUBuglyMgr 需要开启 android:usesCleartextTraffic");
                        }
                    }

                    string[] permissions = new string[] {
                        "android.permission.INTERNET",
                        "android.permission.ACCESS_NETWORK_STATE",
                        "android.permission.ACCESS_WIFI_STATE",
                    };
                    foreach (var permission in permissions)
                    {
                        if (!Permission.HasUserAuthorizedPermission(permission))
                        {
                            ToastText("XUBuglyMgr 缺少权限" + permission);
                            Debug.LogError("XUBuglyMgr 缺少权限" + permission);
                        }
                    }

                    //初始化Bugly
                    BuglyAgent.InitWithAppId(appIdAndroid);
                }
                else if (Application.platform == RuntimePlatform.IPhonePlayer)
                {
                    //初始化Bugly
                    BuglyAgent.InitWithAppId(appIdiOS);
                }

                // 启动C#异常日志捕获上报，默认自动上报级别LogError，那么LogError、LogException的异常日志都会自动捕获上报。
                // 日志级别定义参考LogSeverity: { LogDebug、LogWarning、LogAssert、LogError、LogException}
                BuglyAgent.ConfigAutoReportLogLevel(logSeverity);
                BuglyAgent.EnableExceptionHandler();
            }
        }

        /// <summary>
        /// 修改应用默认配置信息：渠道号、版本、用户标识、Android初始化延时等。
        /// </summary>
        public static void ConfigDefault(string channel, string version, string user, long delay = 0)
        {
            BuglyAgent.ConfigDefault(channel, version, user, delay);
        }

        /// <summary>
        /// 设置用户ID
        /// </summary>
        public static void SetUserId(string userId)
        {
            BuglyAgent.SetUserId(userId);
        }

        /// <summary>
        /// 上报异常
        /// </summary>
        public static void ReportException(Exception ex, string message)
        {
            BuglyAgent.ReportException(ex, message);
        }

        //=======================================================================================================================

        private static int GetAndroidVersion()
        {
#if UNITY_ANDROID
            var version = new AndroidJavaClass("android.os.Build$VERSION");
            var sdkInt = version.GetStatic<int>("SDK_INT");
            return sdkInt;
#else
            return 0;
#endif
        }

        private static bool GetUsesCleartextTraffic(int version)
        {
#if UNITY_ANDROID
            if (version >= 23)
            {
                using (AndroidJavaClass javaClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
                {
                    using (AndroidJavaObject currentActivity = javaClass.GetStatic<AndroidJavaObject>("currentActivity"))
                    {
                        AndroidJavaObject packageManager = currentActivity.Call<AndroidJavaObject>("getPackageManager");
                        AndroidJavaObject packageInfo = packageManager.Call<AndroidJavaObject>("getPackageInfo", Application.identifier, 0);
                        AndroidJavaObject applicationInfo = packageInfo.Get<AndroidJavaObject>("applicationInfo");

                        AndroidJavaClass ApplicationInfo = new AndroidJavaClass("android.content.pm.ApplicationInfo");
                        int FLAG_USES_CLEARTEXT_TRAFFIC = ApplicationInfo.GetStatic<int>("FLAG_USES_CLEARTEXT_TRAFFIC");

                        bool usesCleartextTraffic = (applicationInfo.Get<int>("flags") & FLAG_USES_CLEARTEXT_TRAFFIC) != 0;
                        return usesCleartextTraffic;
                    }
                }
            }
#endif
            return false;
        }

        private static void ToastText(object content)
        {
#if UNITY_ANDROID
            using (AndroidJavaClass javaClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
            {
                using (AndroidJavaObject currentActivity = javaClass.GetStatic<AndroidJavaObject>("currentActivity"))
                {
                    AndroidJavaClass toast = new AndroidJavaClass("android.widget.Toast");
                    AndroidJavaObject context = currentActivity.Call<AndroidJavaObject>("getApplicationContext");
                    currentActivity.Call("runOnUiThread", new AndroidJavaRunnable(() =>
                    {
                        AndroidJavaObject javaString = new AndroidJavaObject("java.lang.String", content.ToString());
                        toast.CallStatic<AndroidJavaObject>("makeText", context, javaString, toast.GetStatic<int>("LENGTH_SHORT")).Call("show");
                    }
                    ));
                }
            }
#endif
        }
    }
}